package com.itheima.controller;


import com.itheima.utils.AliOSSProperties;
import com.itheima.entity.Result;
import com.itheima.utils.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
public class UploadController {

    //文件上传本地存储
//    @PostMapping("/upload")
//    public Result upload(String name, Integer age, MultipartFile file) throws IOException {
//        log.info("参数：{},{},{}",name,age);
//        //将前端上传的文件存储在本地
//
//        //1.获取原始文件名
//        String originalFilename = file.getOriginalFilename();
//
//        //2.通过UUID生成随机字符串
//        String newFileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
//
//
//        file.transferTo(new File("D:\\"+newFileName));
//        return Result.success(newFileName);
//    }

//    //阿里云地址
//    @Value("${aliyun.oss.endpoint}")
//   private String endpoint ;
//   //桶空间名
//    @Value("${aliyun.oss.bucketName}")
//   private String bucketName ;

    @Autowired
    private AliOSSProperties aliOSSProperties;

    /*
    文件上传阿里云OSS存储
    @param file

    */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("参数：{}",file.getOriginalFilename());
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //调用阿里云OSS工具类，将文件上传到oss
        String url = AliyunOSSUtils.upload(aliOSSProperties.getEndpoint(), aliOSSProperties.getBucketName(), file.getBytes(), substring);
        //返回图片路径
        return Result.success(url);
    }
}
